#!/usr/bin/env python
# -*- coding: utf-8 -*-

#Piglenti, written in Python programming language allows you to-day tasks easily integrated with pidgin running a small Linux application.
#Copyright (C) 2010  h4ckinger dot gmail dot com
#www.h4ckinger.org

#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.

#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.

#You should have received a copy of the GNU General Public License
#along with this program.  If not, see <http://www.gnu.org/licenses/>.

from subprocess import Popen,PIPE
from hashlib import md5,sha1
from base64 import b64encode,b64decode
from urlparse import urlparse
from urllib import URLopener,urlencode
from cStringIO import StringIO
import re, gtk.gdk, xml.dom.minidom
import pycurl as curl
from tempfile import gettempdir
from os.path import sep as SEPERATOR
from os import unlink
class fonks:
    """ Functions Class """
    def __init__(self,word):
        """Definations"""
        self.param1     =   None    #param1
        self.param2     =   None    #param2
        self.param3     =   None    #param3
        self.paramText  =   None    #param Text -> "here"
        self.pig        =   word
        self.functions  =   {
                            "help":{
                                    "def":"helpMe",
                                    "help":self.helpMe.__doc__,
                                    "desc":""" for more information and examples type '%shelp funcname' or just type '%shelp' to general information """ % ((self.pig,)*2)
                                    },
                            "google":{
                                    "def":"searchGoogle",
                                    "help":self.searchGoogle.__doc__,
                                    "desc":""" '%sgoogle h4ckinger' or in quoted -> %sgoogle "Coded by h4ckinger" """ % ((self.pig,)*2)
                                    },
                            "screen":{
                                    "def":"screenShot",
                                    "help":self.screenShot.__doc__,
                                    "desc":""" '%sscreen' """ % self.pig
                                    },
                            "md5":{
                                    "def":"generateMd5",
                                    "help":self.generateMd5.__doc__,
                                    "desc":""" '%smd5 123456'\t-> e10adc3949ba59abbe56e057f20f883e """ % self.pig
                                    },
                            "base64":{
                                    "def":"base64enc_dec",
                                    "help":self.base64enc_dec.__doc__,
                                    "desc":""" '%sbase64 string'\t->Encodes string to base64\n'%sbase64 "string and other ones"'\t->Encodes string that in quotes to base64\n'%sbase64 decode string'\t->Decodes string to plaintext\n'%sbase64 decode "string and other ones"'\t->Decodes strings that in quotes to plaintext """ % ((self.pig,)*4)
                                    },
                            "sha1":{
                                    "def":"generateSha1",
                                    "help":self.generateSha1.__doc__,
                                    "desc":"""'%ssha1 123456'\t->7c4a8d09ca3762af61e59520943dc26494f8941b""" % self.pig
                                    },
                            "exec":{
                                    "def":"execShell",
                                    "help":self.execShell.__doc__,
                                    "desc":"""Executes unix commands and returns output '%sexec ls' or '%sexec "ls -la /home/h4ckinger"'""" % ((self.pig,)*2)
                                    },
                            "params":{
                                    "def":"params",
                                    "help":self.params.__doc__,
                                    "desc":"""to test parameters '%sparams param1 param2 param3 "paramText"'""" % self.pig
                                    },
                            }
    def searchGoogle(self):
        """ returns google results of keyword """
        keyword         =self.paramText if self.paramText else self.param2
        rgx_desen       =re.compile("<h3 class=\"r\"><a href=\"(.*?)\" class=l")
        encoded_qstring =urlencode({"q":keyword, "num":"10","start":int(self.param3)*10 if self.param3 and self.param3.isdigit() else 0 })
        google_url      ="http://www.google.com/search?"+encoded_qstring
        headerimiz      = [ ('user-agent' , "Opera/9.21 (Windows NT 5.1; U; tr)") ]
        opener          = URLopener()
        opener.addheaders=headerimiz
        source          = opener.open(google_url).read()
        matches         =re.findall(rgx_desen, source)
        return matches
    def screenShot(self):
        """ Takes a screenshot of desktop and uploads that to imageshack.us"""
        w = gtk.gdk.get_default_root_window()
        sz = w.get_size()
        pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1])
        pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1])
        if pb:
            scr =gettempdir()+SEPERATOR+"screenshot.png"
            pb.save(scr,"png")
            #uploading
            resp    = StringIO()
            data = [('xml','yes'),('fileupload', (curl.FORM_FILE, scr))]
            req = curl.Curl()
            req.setopt(curl.URL, 'http://www.imageshack.us/index.php')
            req.setopt(curl.HTTPPOST, data)
            req.setopt(curl.WRITEFUNCTION, resp.write)
            req.setopt(curl.VERBOSE,0)
            req.perform()
            req.close()
            unlink(scr) #delete tmp screen
            src=resp.getvalue()
            #parsing
            dom=xml.dom.minidom.parseString(src)
            element=dom.getElementsByTagName("image_link")[0]
            return str("Uploaded screenshot : %s" % element.firstChild.data)
        else:
            return "Couldn't get screenshot"

    def generateMd5(self):
        """ returns md5 hash of string """
        return md5(self.param2).hexdigest()
    def generateSha1(self):
        """ returns sha1 hash of string"""
        return sha1(self.param2).hexdigest()
    def base64enc_dec(self):
        """ base64 encode,decode """
        st  =   self.paramText if self.paramText else (self.param2 if not self.param3 else self.param3)
        return b64decode(st) if self.param2 == "decode" and self.param3  else b64encode(st)
    def execShell(self):
        """ execute shell command """
        ret=""
        try:
            r   = Popen(self.paramText.split(" ") if self.paramText else self.param2, stdout=PIPE)
            ret = r.stdout.read()
        except OSError:
            pass
        return ret.splitlines()
    def params(self):
        """ shows params """
        return str("self.param1 =%s \n self.param2 = %s \n self.param3 = %s \n self.paramText = %s" % (self.param1,self.param2,self.param3,self.paramText))
    def helpMe(self):
        """ help function """
        yaz =   "".join(["%s: %s\n" % (x,self.functions[x]["help"]) for x in self.functions.keys()]) if not self.param2 or not self.functions.has_key(self.param2) else self.functions[self.param2]["desc"]
        return """\n%s \nType /pig help function""" %  yaz